import { defineStore } from 'pinia';
import { updateAuthInfoApi } from 'src/api/auth';
import { getAuthInfoApi, getInfoApi, getUserInfoApi, loginApi } from 'src/api/user';
import { getUrlParam } from 'src/boot/paramhandler';
import { showLoadingToast } from 'vant';
import { v4 as uuidv4 } from 'uuid';
export type UserAuthInfo = {
  idcard: string;
  authFlag: number;
  realname: string;
};
export type UserInfo = {
  token: string;
  channelCode: string;
  channelName: string;
  regChannelCode: string;
  regChannelName: string;
  uid: string;
  username: string;
  mobile: string;
  authFlag: number;
  faceFlag: number;
  sourceFlag: number;
  limitAmount: number;
  userAuthInfo: UserAuthInfo;
};

let tokenLoginPromise: Promise<UserInfo> | undefined;

type PageType = 'auth_list' | 'auth_download' | 'list' | 'download' | 'auth' | 'auth_match' | 'auth_over';

export const useAppStore = defineStore('app', {
  state: () => {
    const { param } = getUrlParam();
    return {
      token: localStorage.getItem('token') ?? '',
      channelCode: localStorage.getItem('channelCode') || `${param.channelCode}`,
      deviceId: `${param.deviceId ?? ''}` || localStorage.getItem('deviceId') || uuidv4(),
      userInfo: {} as UserInfo,
      mobile: localStorage.getItem('mobile') ?? '',
      smsFlag: localStorage.getItem('smsFlag') ?? 0,
      channelName: localStorage.getItem('channelName') ?? 0,
      pageType: (localStorage.getItem('pageType') ?? 'auth_list') as PageType,
      chargeType: undefined as number | undefined,
      isInitPage: false,
    };
  },
  getters: {
    isLogin: (state) => !!state.token,
    isSMS: (state) => +state.smsFlag == 1,
    isAuth: (state) => state.userInfo.authFlag == 1,
    getAuthInfoData: (state) => {
      const info = state.userInfo.userAuthInfo ?? {};
      const tempInfo = {
        idcard: info.idcard || localStorage.getItem('idcard'),
        realname: info.realname || localStorage.getItem('realname'),
      };
      const authFlag = tempInfo.idcard && tempInfo.realname ? 1 : 0;
      return {
        authFlag,
        ...tempInfo,
      };
    },
    getSafePhone: (state) => {
      if (state.userInfo?.mobile) return state.userInfo?.mobile
      if (state.mobile.length !== 11) return state.mobile
      return `${state.mobile.slice(0,3)}*****${state.mobile.slice(state.mobile.length - 3, state.mobile.length)}`
    }
  },
  actions: {
    async updateAuthInfo(idcard: string, realname: string) {
      await updateAuthInfoApi({
        idcard: idcard,
        realname: realname,
      });
      localStorage.setItem('idcard', idcard);
      localStorage.setItem('realname', realname);
      // this.userInfo.authFlag = 1
      await this.getUserInfo();
    },
    async login(phone: string, code?: string) {
      const res = await loginApi({ loginType: code ? 0 : 3, mobile: phone, loginCode: code });
      this.token = res.data.token;
      localStorage.setItem('mobile', phone);
      localStorage.setItem('token', res.data.token);
      await this.getUserInfo();
    },
    async tokenLogin(token: string) {
      if (token === this.token) {
        if (tokenLoginPromise) return await tokenLoginPromise;
        return await this.getUserInfo();
      }
      this.token = token;
      localStorage.setItem('token', token);
      tokenLoginPromise = this.getUserInfo();
      return await tokenLoginPromise;
    },
    async jointLogin(phone: string) {
      const res = await loginApi({ loginType: 7, mobile: phone }, { diyError: true });
      const resUserInfo = await getUserInfoApi({ token: res.data.token }, { diyError: true });
      this.token = res.data.token;
      localStorage.setItem('mobile', phone);
      localStorage.setItem('token', res.data.token);
      await this.setUserInfo(resUserInfo.data);
    },
    async setUserInfo(_userInfo: UserInfo) {
      const userInfo = {} as UserInfo;
      userInfo.token = _userInfo?.['token'] ?? '';
      userInfo.uid = _userInfo?.['uid'] ?? '';
      userInfo.regChannelName = _userInfo?.['regChannelName'] ?? '';
      userInfo.regChannelCode = _userInfo?.['regChannelCode'] ?? '';
      userInfo.regChannelCode = _userInfo?.['regChannelCode'] ?? '';
      userInfo.authFlag = _userInfo?.['authFlag'] ?? 0;
      userInfo.channelCode = _userInfo?.['channelCode'] ?? '';
      userInfo.username = _userInfo?.['username'] ?? '';
      userInfo.mobile = _userInfo?.['mobile'] ?? '';
      userInfo.sourceFlag = _userInfo?.['sourceFlag'] ?? 0;
      userInfo.limitAmount = _userInfo?.['limitAmount'] ?? 0;
      this.userInfo = userInfo;
      if (userInfo.authFlag == 1) {
        await this.getAuthInfo();
      }
    },
    async getUserInfo() {
      const res = await getUserInfoApi<UserInfo>();
      this.setUserInfo(res.data);
      return res.data;
    },
    async getAuthInfo() {
      const res = await getAuthInfoApi();
      const userAuthInfo = {} as UserAuthInfo;
      userAuthInfo.authFlag = res.data?.['authFlag'] ?? 0;
      userAuthInfo.idcard = res.data?.['idcard'] ?? '';
      userAuthInfo.realname = res.data?.['realname'] ?? '';
      this.userInfo.userAuthInfo = userAuthInfo;
    },
    async initPage() {
      const res = await getInfoApi<{
        smsFlag: string | number;
        channelName: string;
        pageType: 'download' | 'auth_list' | 'auth_download' | 'list' | 'auth';
        chargeType: number;
        channelCode: string;
      }>();
      const { smsFlag, channelName, pageType, chargeType } = res.data;
      this.smsFlag = smsFlag;
      this.channelName = channelName;
      this.pageType = pageType;
      this.chargeType = +chargeType;
      localStorage.setItem('smsFlag', `${smsFlag}`);
      localStorage.setItem('channelName', channelName);
      localStorage.setItem('chargeType', `${chargeType}`);
      localStorage.setItem('pageType', `${pageType}`);
      this.isInitPage = true;
      return res.data;
    },
  },
});
